import React, { Component, Fragment } from 'react';
import Upload from './../../components/Upload/indexwhole';
import Buttons from './../../components/Buttons';
import { Button, Breadcrumb, Checkbox,Empty } from 'antd';
import { PlusOutlined, AppstoreOutlined, MenuOutlined } from '@ant-design/icons';
import axios from './../../axios';
import FileList from './../../components/FileList';
import FileListThumb from './../../components/FileListThumb';
import CreateFolder from './../../components/CreateFolder';
import { connect } from 'react-redux';
import store from './../../store';
import './index.less';

let linshi = "";
class Whole extends Component {
	
	constructor(props){
		super(props);
		this.state = {
			requestParams: {//请求列表数据的参数
				pid: 0
			},
			pid: 0,//当前所在目录层级
			res: false,
			filelist: [],//文件列表
			checkedArr: [],//选中项
			showCheckboxAll: false,//全选checkbox框
			view_mode: "list",//列表显示或矩阵显示
			isCreateFolder: false,//新建文件夹状态
			item:{}
		};
	}
	
	componentWillUnmount(){
		this.unsubscribe();
	}
	
	componentDidMount(){
		this.unsubscribe = store.subscribe(this.handleStoreChange);
		this.requestList(this.state.requestParams);
		const view_mode = localStorage.getItem("jqmkj_whole_view_mode");
		if(view_mode){
			this.setState({view_mode});
		}
		const fileid = sessionStorage.getItem("fileid");
		if(!fileid){
			sessionStorage.setItem("fileid", 0);
		}
	}
	
	//切换列表显示或矩阵显示
	changeViewMode = (view_mode) => {
		this.setState({view_mode});
		localStorage.setItem("jqmkj_whole_view_mode", view_mode);
	}
	
	//全局搜索
	handleStoreChange = () => {
		const value = store.getState().searchValue;
		if(value){
			if(linshi === value){
				return
			}else{
				linshi = value
				axios.get({
					url: "/files/page/search", 
					method: "get",
					params: {search: value},
				}).then(res=>{
					if(res.code === 0 && res.result.list){
						let resData = res.result.list.map((item, index)=>{
							let checked = false;
							return {...item, checked}
						})
						this.setState({
							filelist: resData,
							count: res.result.pagination.count,
							checkedArr: []
						})
					}
				})
			}
		}
	}
	
	//刷新列表
	refreshList = () => {
		setTimeout(()=>{
			this.requestList(this.state.requestParams);
		},1000)
	}
	
	//获取文件列表
	requestList = (data) => {
		let fileid = sessionStorage.getItem("fileid");
		let breArr = sessionStorage.getItem("breadcrumb");
		let breadcrumbArr = null;
		if(breArr && breArr !== "undefined"){
			breadcrumbArr = JSON.parse(breArr);
		}
		let reqdata = data;
		if(fileid){
			reqdata.pid = fileid;
		}
		if(breadcrumbArr){
			let breadcrumbList = breadcrumbArr.map(item => {
				return <Breadcrumb.Item key={item.fileid} onClick={()=>this.folderClick(item.fileid,item.filename)}>{item.filename}</Breadcrumb.Item>
			})
			this.setState({breadcrumbList});
		}else{
			breadcrumbArr = [{fileid: 0, filename: "全部"}];
			sessionStorage.setItem("breadcrumb", JSON.stringify(breadcrumbArr));
			let breadcrumbList = breadcrumbArr.map(item => {
				return <Breadcrumb.Item key={item.fileid} onClick={()=>this.folderClick(item.fileid,item.filename)}>{item.filename}</Breadcrumb.Item>
			})
			this.setState({breadcrumbList});
		}
		axios.get({
			url: "/files/page/local", 
			method: "get",
			params: reqdata,
		}).then(res=>{
			if(res.code === 0 && res.result.list){
				let resData = res.result.list.map((item, index)=>{
					let checked = false;
					return {...item, checked}
				})
				this.setState({
					filelist: resData,
					count: res.result.pagination.count,
					checkedArr: [],
					res: true
				})
			}
		}).catch(err=>{
		})
	}
	
	//点击进入文件夹
	folderClick = (fileid, filename) => {
		let breadcrumbArr = JSON.parse(sessionStorage.getItem("breadcrumb"));
		if(!breadcrumbArr){
			breadcrumbArr = [{fileid: 0, filename: "全部"}];
		}
		let flag = false;
		for(let i = 0; i < breadcrumbArr.length; i++){
			if(breadcrumbArr[i].fileid === fileid){
				breadcrumbArr = breadcrumbArr.slice(0,i+1);
				flag = true;
			}
		}
		if(!flag){
			breadcrumbArr.push({fileid,filename});
		}
		sessionStorage.setItem("breadcrumb", JSON.stringify(breadcrumbArr));
		let breadcrumbList = breadcrumbArr.map(item => {
			return <Breadcrumb.Item key={item.fileid} onClick={()=>this.folderClick(item.fileid,item.filename)}>{item.filename}</Breadcrumb.Item>
		})
		let requestParams = {
			pid: fileid
		}
		this.setState({breadcrumbList,requestParams,pid:fileid})
		sessionStorage.setItem("fileid", fileid);
		this.requestList({pid: fileid});
	}
	
	checkedClick = (checkedArr) => {
		this.setState({
			checkedArr
		})
	}
	
	//新建文件夹
	createFolder = (isSuccess) => {
		this.setState({
			isCreateFolder: false
		});
		if(isSuccess){
			//新建后重新刷新列表
			setTimeout(()=>{
				//重新请求数据
				this.requestList(this.state.requestParams);
			},1000)
		}
	}
	
	//点击全选checkbox框
	clickCheckboxAll = e => {
		this.props.checkboxAll(e.target.checked);
	}
	
	async shouldComponentUpdate(nextProps, nextState){
		if( nextProps.item && nextProps.item.hasOwnProperty('parentid')){
			
			sessionStorage.setItem("fileid", nextProps.item.parentid)
			if (nextState.item.parentid !== nextProps.item.parentid) { 
				let parentid = nextProps.item.parentid;
				const {result} = await axios.get({url:'/files/file/dirTree',method:'get'});
				let bre = {};
				bre[0] = [{fileid: 0, filename: "全部"}]
				
				function searchDir(dir){
					dir.forEach(item=>{
						bre[item.id] = bre[item.parentid]?[...bre[item.parentid]]:[]
						bre[item.id].push({fileid:item.id,filename:item.filename})
						item.children && searchDir(item.children)
					})
				}
				searchDir(result)
				let breArr = bre[nextProps.item.parentid];
				sessionStorage.setItem("breadcrumb", JSON.stringify(breArr));
				let breadcrumbList = [];
				if(breArr){
					breadcrumbList = breArr.map(item => {
						return <Breadcrumb.Item key={item.fileid} onClick={()=>this.folderClick(item.fileid,item.filename)}>{item.filename}</Breadcrumb.Item>
					})
				}
				let requestParams = {
					pid: parentid
				}                                                   
				this.setState({breadcrumbList,requestParams,pid:parentid,item:nextProps.item})
				this.requestList(requestParams);
				
				return true;
				
			}
		}
		return true
	}
	
	render(){
		const hasSelectedLength = this.state.checkedArr.length;
		const { showCheckboxAll } = this.state;
		const pid = sessionStorage.getItem("fileid");
		return (
			<div className="page-wrap">
				<div className="page-header">
					{
						hasSelectedLength > 0 ? <Buttons checkedArr={this.state.checkedArr} /> :
						<div className="upload-wrap">
							<Upload pid={pid} refreshList={this.refreshList} />
							<Button
								icon={<PlusOutlined />}
								onClick={()=>this.setState({isCreateFolder: true})}
								type="primary"
								ghost
							>
								新建文件夹
							</Button>
						</div>
					}
					<div className="change-show">
						{this.state.view_mode === "list" ? 
							<AppstoreOutlined
								className={this.state.view_mode === "thumb" ? "active" : ""}
								onClick={()=>this.changeViewMode("thumb")}
							/>:
							<MenuOutlined 
								className={this.state.view_mode === "list" ? "active" : ""}
								onClick={()=>this.changeViewMode("list")} 
							/>
						}
					</div>
				</div>
				<div className="page-content">
					<div className="breadcrumb">
						<Breadcrumb>
							{
								this.state.breadcrumbList
							}
						</Breadcrumb>
					</div>
					{ 
						hasSelectedLength > 0 ?
						<div className="selected-num">
							已选择{hasSelectedLength} 项
						</div> : ""
					}
					{
						this.state.filelist.length > 0 || this.state.isCreateFolder? 
						<div
							className="line-header"
							onMouseEnter={()=>this.setState({showCheckboxAll:true})}
							onMouseLeave={()=>this.setState({showCheckboxAll:false})}
						>
							{   (hasSelectedLength > 0 || showCheckboxAll) ?
								<div className="checkboxall-wrap">
									<Checkbox onClick={(e)=>this.clickCheckboxAll(e)} />
								</div>:""
							}
							<div className="border-bottom">
								<span>文件名</span>
								{this.state.view_mode === "list" ? 
									<Fragment>
										<span className="w200 float-right">上次修改时间</span>
										<span className="w200 float-right">大小</span>
									</Fragment>:""
								}
							</div>
						</div>:""
					}
					{this.state.isCreateFolder?
						<CreateFolder pid={pid} createFolder={this.createFolder} /> : ""
					}
					{
						this.state.filelist.length > 0 ? 
						<div className="file-wrap" style={{height: "calc(100% - 80px)"}}>
							{ 
								this.state.view_mode === "list" ? 
								<FileList
									filelist={this.state.filelist}
									folderClick={this.folderClick}
									refreshList={this.refreshList}
									checkedClick={this.checkedClick}
									contextMenuType="whole"
								/>:
								<FileListThumb
									filelist={this.state.filelist}
									folderClick={this.folderClick}
									refreshList={this.refreshList}
									checkedClick={this.checkedClick}
									contextMenuType="whole"
								/>
							}
							<p style={{textAlign: "center", clear: "both"}}>共{this.state.count}项</p>
						</div>
						: this.state.isCreateFolder? "": this.state.res?
						<div className="empty-page">
							<div>
								<Empty description='暂无数据'/>
							</div>
						</div>:""
					}
				</div>
			</div>
		)
	}
}

const mapState = (state) => {
	return {
		item: state.item,
		searchValue: state.searchValue
	}
}

const mapDispatch = (dispatch) => {
	return {
		checkboxAll(isCheckedAll){
			dispatch({
				type: "CHECKBOX_ALL",
				isCheckedAll
			})
		}
	}
}

export default connect(mapState, mapDispatch)(Whole);